<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.alipay.api.internal.util.AlipaySignature" %>
<%@ page import="com.example.config.AlipayConfig" %>
<%@ page import="com.example.dao.NovelDao" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="com.alipay.api.AlipayApiException" %>

<%
    // 获取支付宝POST过来的信息
    Map<String,String> params = new HashMap<String,String>();
    Map<String,String[]> requestParams = request.getParameterMap();
    for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
        String name = iter.next();
        String[] values = requestParams.get(name);
        String valueStr = "";
        for (int i = 0; i < values.length; i++) {
            valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
        }
        params.put(name, valueStr);
    }

    // 验证签名
    boolean signVerified = false;
    try {
        signVerified = AlipaySignature.rsaCheckV1(
                params,
                AlipayConfig.alipay_public_key,
                AlipayConfig.charset,
                AlipayConfig.sign_type
        );
    } catch (AlipayApiException e) {
        throw new RuntimeException(e);
    }

    if(signVerified) {
        // 商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        // 支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
        // 交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

        if (trade_status.equals("TRADE_SUCCESS")) {
            // 更新订单状态
            NovelDao orderDao = new NovelDao();
            orderDao.updateOrderStatus(trade_no, "已支付");
            out.println("success");
        }
    } else {
        out.println("fail");
    }
%>